<?php

class Objects_model extends Onecore_Model
{

    public function __construct()
    {
        parent::__construct();
        $this->_name = "objects";
        $this->_id = array("id");
        $this->_fields = array("id","name","description","type_objects_id","category_id");
        $this->_fieldsConditions = array("ModuloId"=>"where","name"=>"like","description"=>"like");
        $this->_itemName = "Objeto Tema";
        $this->_validations = array(
            array(
                "field"=>"name",
                "label"=>"name",
                "rules"=>"required"
            ),
            array(
                "field"=>"type_objects_id",
                "label"=>"Tipo de Tema",
                "rules"=>"required"
            ),
            array(
                "field"=>"category_id",
                "label"=>"Categoria",
                "rules"=>"required"
            )
        );
        
    }
    
    public function getFull($id){
        $cfg = (object)$this->config->item('defaultCfg');

        $this->load->model("categories_model");
        $this->load->model("elem_test_model");
        $this->load->model("elem_questions_model");
        $this->load->model("elem_questions_answers_model");
        $this->load->model("elem_ppt_model");
        $this->load->model("elem_ppt_slide_model");
        $this->load->model("objects_objects_model");

        $object = $this->getByid($id);
        if(!empty($object[0])){
            $object = $object[0];

            $object->name = html_entity_decode($object->name);
            $object->description = html_entity_decode($object->description);

            //categoria
            $category = $this->categories_model->getByid($object->category_id);
            if(!empty($category[0])){
                $object->category = $category[0];                
            }

            //buscamos si tiene ppt
            $ppt = $this->elem_ppt_model->getByobjects_id($object->id);
            if(is_array($ppt) && !empty($ppt[0])){
                $object->presentation = $ppt[0];

                $object->presentation->name = html_entity_decode($object->presentation->name);
                $object->presentation->description = html_entity_decode($object->presentation->description);

                $object->presentation->slides = $this->elem_ppt_slide_model->getByelem_presentations_id($object->presentation->id);
            }

            //buscamos prueba
            $test = $this->elem_test_model->getByobjects_id($object->id);
            if(is_array($test) && !empty($test[0])){
                $object->test  = $test[0];
                $object->test->title = html_entity_decode($object->test->title);
                $object->test->description = html_entity_decode($object->test->description);

                $object->test->questions  = $this->elem_questions_model->getQuestionsByTest($object->test->id);
            }  

            //buscamos objetos relacionados
            $relatedObjects = $this->getByparent($object->id);
            if(!empty($relatedObjects)){
                $aux = array();
                foreach($relatedObjects as $related){
                    if($related->type_objects_id != $cfg->type_object_note &&
                        $related->type_objects_id != $cfg->type_object_request){
                        $aux[] = $related;
                    }
                }
                $object->relatedObjects = $aux;
            }  

            //obtenemos objeto faq
            $query = new stdClass();
            $query->conditions = new stdClass();
            $query->conditions->type_objects_id = $cfg->type_object_faq;
            $faq = $this->listEntities($query);
            //obtenemos test asociado al faq
            if(count($faq['items'])>0){
                $faq  = $faq['items'][0];
                //buscamos prueba
                $testFaq = $this->elem_test_model->getByobjects_id($faq->id);
                if(is_array($testFaq) && !empty($testFaq[0])){
                    $object->faq = $faq;
                    $object->faq->test  = $testFaq[0];
                    $object->faq->test->questions  = $this->elem_questions_model->getQuestionsByTest($object->faq->id);
                }   
            }
        }   
        else{
            $object = null;
        }
        return $object;
    }

    public function loadListCrud($options){
        $this->load->model("elem_test_model");
        $this->load->model("elem_questions_model");
        $this->load->model("elem_questions_answers_model");
        $this->load->model("elem_ppt_model");
        $this->load->model("elem_ppt_slide_model");
        $this->load->model("users_exec_model");
        $this->load->model("users_model");
        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");

        $cfg = (object)$this->config->item('defaultCfg');

        $items = array();
        $condition = "";
        $count = 0;
        foreach($options->conditions as $key=>$value){
            if(!empty($value)){
                if($key == "o.name" || $key == "o.description" || $key == "o.ucreated" || $key == "o.umodified")
                    $condition .= "and $key like '%$value%' "; 
                else{
                    if($key != "from" && $key != "to"){
                        $condition .= "and $key = '$value' "; 
                    }
                }
            }  
        }

        if(!empty($options->conditions->from)){
            $from = $options->conditions->from;
            $condition .= "and o.dcreated >= '$from' ";
        }
            
        if(!empty($options->conditions->to)){
            $to = $options->conditions->to;
            $condition .= "and o.dcreated <= '$to' ";
        }

        //si quiere ver los eliminiados
        if($options->conditions->deleted != ""){
            $deleted = $options->conditions->deleted;
            $condition .= "and o.deleted = '$deleted' ";
        }        

        //obtenemos total de rtegistros sin filtros
        $count=0;
        $sqlCount = "select count(*) as count 
                    from $this->_name o, categories c, users u 
                    where   o.category_id = c.id
                    and     o.users_id = u.id
                    $condition";

        $queryCount = $this->db->query($sqlCount);        
        if ($queryCount->num_rows() > 0){
            $resultCount = $queryCount->result();
            $count = $resultCount[0]->count;
        }    

        $sql = "select  o.*, c.name as category_name, 
                        concat(o.name,' - v',o.version) as name_version,
                        u.names as autor_names,
                        u.lastnames as autor_lastnames,
                        concat(u.names,' ',u.lastnames) as autor_fullname,
                        u.email as autor_email
                from $this->_name o, categories c , users u 
                where o.category_id = c.id
                and     o.users_id = u.id
                $condition
                order by $options->orderField $options->orderDirection
                LIMIT   $options->start, $options->limit";
        $query = $this->db->query($sql);    

        $aux = array();

        if ($query->num_rows() > 0){
            $items = $query->result();


           // print_r($items);exit;

            for ($i=0; $i < count($items); $i++) { 
                $test = $this->elem_test_model->getByobjects_id($items[$i]->id);
                if(is_array($test) && !empty($test[0])){
                    $items[$i]->test_id  = $test[0]->id;
                }
                $ppt = $this->elem_ppt_model->getByobjects_id($items[$i]->id);
                if(is_array($ppt) && !empty($ppt[0])){
                    $items[$i]->presentation_id = $ppt[0]->id;
                    $items[$i]->presentation_name = html_entity_decode($ppt[0]->name);
                    $items[$i]->presentation_description = html_entity_decode($ppt[0]->description);
                }

                //si la lista debe incluir hit de usuario asociado al obejto
                if($options->includeHit == "true"){
                    $conditions = new stdClass();
                    $conditions->users_id = $options->users_id;
                    $conditions->objects_id = $items[$i]->id;
                    $conditions->type_objects_id = $items[$i]->type_objects_id;
                    $items[$i]->hit = $this->users_exec_model->lastHit($conditions);
                }

                //si la lista debe incluir objetos relacionados
                if($options->includeRelatedObjects == "true"){
                    $relateds = $this->getByparent($items[$i]->id);
                    $items[$i]->relatedObjects = array();
                    //pasamos si posee una nota
                    for ($j=0; $j < count($relateds); $j++) { 
                        if($relateds[$j]->type_objects_id != $cfg->type_object_note){
                            //si es nota de derivacion lo asignamos a objeto principal
                            if($relateds[$j]->category_id == $cfg->category_referralnote){
                                $items[$i]->referralnote = $relateds[$j];
                            }
                            $items[$i]->relatedObjects[] = $relateds[$j];
                        }
                    }
                }
                //si solicita config
                if($options->includeConfig == "true"){
                    $query = new stdClass();
                    $query->conditions = new stdClass();
                    $query->conditions->type_objects_id = $items[$i]->type_objects_id;
                    $query->conditions->groups_id = $options->groups_id;
                    $module = $this->modules_model->listEntities($query);
                    if(!empty($module["items"][0])){
                        $module = $module["items"][0];

                        $items[$i]->modules_id = $module->id;

                        $query = new stdClass();
                        $query->conditions = new stdClass();
                        $query->conditions->objects_id = $items[$i]->id;
                        $query->conditions->modules_id = $module->id;
                        $modules_object = $this->modules_objects_model->listEntities($query);

                        if(!empty($modules_object["items"][0])){
                            $modules_object = $modules_object["items"][0];
                            $modules_object->config = str_replace("&quot;", '"', $modules_object->config);
                            $items[$i]->config = json_decode($modules_object->config);

                            
                            //print_r($modules_object->config);exit;

                            
                        }
                    }
                }
                //si esta filtrando por status de ejecucion
                if(!empty($items[$i]->hit) && !empty($options->hitStatus)){
                    if( $items[$i]->hit->status == $options->hitStatus){
                        $aux[] = $items[$i];
                    }
                }
                
            }
            //filtramos si se eselecciono algun estado de ejecucion
            if(!empty($options->hitStatus))    $items = $aux;

            //filtramos si esta buscando temas segun cierre y apertura
            if(!empty($options->startExec) || !empty($options->endExec)){
                $aux = array();
                for ($i=0; $i < count($items); $i++) { 
                    //si flitra por ambas fechas
                    if(!empty($options->startExec) && !empty($options->endExec)){
                        if( strtotime($items[$i]->config->start) >= strtotime($options->startExec) && 
                            strtotime($items[$i]->config->end) <= strtotime($options->endExec)      ){
                            $aux[] = $items[$i];
                        }
                    }
                    else{
                        //si solo filtra por apertura tema
                        if(!empty($options->startExec) && empty($options->endExec)){
                            if(strtotime($items[$i]->config->start) >= strtotime($options->startExec) ){
                                $aux[] = $items[$i];
                            }
                        }
                        else{
                            //si filtra solo por cierre
                            if(strtotime($items[$i]->config->end) <= strtotime($options->endExec)){
                                $aux[] = $items[$i];
                            }
                        }
                    }
                }
                $items = $aux;
            }
            

            
        }   
        $res = array(
            'results' => $count,
            'items' => $items
        );
        return $res;
    }

    public function getCategories($moduleId, $type_object_id){
        $sql = "select * from categories where type_objects_id = $type_object_id;";
        $query = $this->db->query($sql);
        return $query->result();       
    }
    
    public function getByModule($moduleid){
        $sql = "select c.name as category, 
                        o.*,
                        t.name as typeobject
                from modules_objects mo, objects o, type_objects t, categories c
                where mo.modules_id = $moduleid
                and mo.objects_id = o.id
                and o.type_objects_id = t.id
                and o.category_id = c.id;";
        $query = $this->db->query($sql);
        return $query->result();       
    }
    public function loadResourceFiles($conditions) {
        $items= array();
        $count=0;
        $sqlCount = "select  count(*) as count from $this->_name";
        
        $queryCount = $this->db->query($sqlCount);        
        if ($queryCount->num_rows() > 0){
            $resultCount = $queryCount->result();
            $count = $resultCount[0]->count;
        }    
        
        $sql = "select  o.*, cat.name as category_name
                from    $this->_name o left join categories cat
                on o.category_id = cat.id
                where   o.parent = $conditions->parent
                and     o.type_objects_id = $conditions->type_objects_id
                order   by $conditions->order $conditions->direction 
                LIMIT   $conditions->start, $conditions->limit";
        
        $query = $this->db->query($sql);    
        if ($query->num_rows() > 0){
            $items = $query->result();
        }   
        $res = array(
            'results' => $count,
            'items' => $items
        );
        return $res;
    }

    
}

